<template>
   <div class="qualification-management">
      <!-- 1. 企业选择区 -->
      <div class="enterprise-selector">
         <el-form inline :model="searchForm">
            <el-form-item label="企业名称">
               <el-select v-model="searchForm.enterpriseId" filterable style="width: 300px;" placeholder="请选择企业"
                  clearable @change="handleEnterpriseChange">
                  <el-option v-for="item in enterpriseList" :key="item.enterpriseId" :label="item.enterpriseName"
                     :value="item.enterpriseId" />
               </el-select>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" @click="handleSearchQualification">查询</el-button>
               <el-button type="primary" @click="handleAddQualification">新增资质文件</el-button>
            </el-form-item>
         </el-form>
      </div>

      <!-- 2. 资质文件列表区 -->
      <div class="qualification-table">
         <el-table :data="qualificationList" row-key="enterpriseQualificationId" :border="true" style="width: 100%">
            <el-table-column prop="enterprisePojo.enterpriseName" label="企业名称" :align="center" width="220" />
            <el-table-column prop="qualificationFileName" label="文件名" min-width="150" :align="center" />
            <el-table-column prop="qualificationFileType" label="文件类型" min-width="120" :align="center">
               <template #default="scope">
                  <el-tag>
                     {{
                        scope.row.qualificationFileType ===
                           'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ? '.docx' :
                           scope.row.qualificationFileType ===
                              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ? '.xlsx' :
                              scope.row.qualificationFileType ===
                                 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ? '.pptx' :
                                 scope.row.qualificationFileType === 'application/msword' ? '.doc' :
                                    scope.row.qualificationFileType === 'application/vnd.ms-excel' ? '.xls' :
                                       scope.row.qualificationFileType === 'application/vnd.ms-powerpoint' ? '.ppt' :
                                          scope.row.qualificationFileType
                     }}
                  </el-tag>
               </template>
            </el-table-column>
            <el-table-column label="文件大小" min-width="100" :align="center">
               <template #default="scope">
                  {{ formatFileSize(scope.row.qualificationFileSize) }}
               </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="上传时间" min-width="160" :align="center" />
            <el-table-column label="操作" width="240" fixed="right" :align="center">
               <template #default="scope">
                  <el-button size="small" @click="handleDownFlie(scope.row)">下载文件</el-button>
                  <!-- <el-button size="small" @click="handlePreview(scope.row)">预览</el-button> -->
                  <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
               </template>
            </el-table-column>
         </el-table>
         <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="page.currentPage" :page-sizes="[10, 20, 50]" :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper" :total="page.total" />
      </div>

      <!-- 3. 新增/编辑弹窗 -->
      <el-dialog v-model="dialogVisible" :draggable="true" :title="isEdit ? '编辑资质文件' : '新增资质文件'" :width="600">
         <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px">
            <el-form-item label="资质文件" prop="fileList">
               <el-upload v-model:file-list="form.fileList" :http-request="customUpload" :limit="1"
                  :file-size="20 * 1024 * 1024" :before-upload="handleBeforeUpload" :on-remove="handleFileRemove"
                  :on-exceed="handleExceed" drag>
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <template #tip>
                     <div class="el-upload__tip">
                        支持上传 jpg、jpeg、png、pdf、mp4、zip等 格式文件，大小不超过 50MB，最多上传 1 个文件
                     </div>
                  </template>
               </el-upload>
            </el-form-item>
         </el-form>

         <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
         </template>
      </el-dialog>
   </div>

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import request from '@/api/request'
import { downloadContract } from '@/api/contract'



const center = 'center'
// 分页参数
const page = ref({
   current: 1,
   size: 10,
   total: 1
})
// 搜索表单（当前选择的企业）
const searchForm = reactive({
   enterpriseId: null
});
// 企业列表数据
const enterpriseList = ref([]);
// 资质文件列表数据
const qualificationList = ref([]);

// 初始化数据
onMounted(() => {
   //加载企业列表数据
   loadEnterpriseList()
   loadQualificationList(null)
});

// 分页-每页条数改变
const handleSizeChange = (val) => {
   page.value.size = val
}

// 分页-当前页改变
const handleCurrentChange = (val) => {
   page.value.current = val
}

//初始化加载企业列表数据
const loadEnterpriseList = () => {
   request.get("qualification/getEnterprise").then(res => {
      if (res.success) {
         enterpriseList.value = [...res.data]
      }
   })
}
//初始化加载资质文件列表数据
const loadQualificationList = async (enterpriseId) => {
   const res = await request.get("qualification/getQualification", {
      params: {
         enterpriseId: enterpriseId,
         pageNum: page.value.current,
         pageSize: page.value.size,
      }
   })
   if (res.success) {
      qualificationList.value = res.data.list
      page.value.total = res.data.total
   } else {
      ElMessage.error("加载企业信息失败")
   }
}

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const form = reactive({
   enterpriseQualificationId: null,
   enterpriseId: null,
   fileList: []
});
const formRules = {
   enterpriseId: [{ required: true, message: '请选择企业', trigger: 'blur' }],
   fileList: [
      {
         required: !isEdit.value,
         message: '请上传资质文件',
         trigger: 'change'
      }
   ],
};
// 选择企业后触发
const handleEnterpriseChange = () => {
   loadQualificationList(searchForm.enterpriseId)
};
const handleSearchQualification = () => {
   loadQualificationList(searchForm.enterpriseId)
}

// 新增资质文件
const handleAddQualification = () => {
   if (!searchForm.enterpriseId) {
      ElMessage.warning('请先选择企业');
      return;
   }
   formRef.value?.resetFields();
   Object.assign(form, {
      enterpriseQualificationId: null,
      enterpriseId: searchForm.enterpriseId,
      fileList: [],
   });
   isEdit.value = false;
   dialogVisible.value = true;
};


//文件下载
const handleDownFlie = async (row) => {
   downloadContract(
      {
         enterpriseQualificationId: row.enterpriseQualificationId
      },
      'qualification/download-file'
   )

}

// 编辑资质文件
const handleEdit = (row) => {
   form.enterpriseQualificationId = row.enterpriseQualificationId;
   form.enterpriseId = row.enterprisePojo.enterpriseId;
   form.fileList = [
      {
         name: row.qualificationFileName,
         url: row.qualificationFilePath,
         uid: row.enterpriseQualificationId,
         status: 'success'
      }
   ];
   isEdit.value = true;
   dialogVisible.value = true;
};

// 文件上传
const customUpload = async (options) => {
   const { file, onSuccess, onError } = options

   try {
      // 创建FormData，包含文件
      const formData = new FormData()
      formData.append('file', file)  // 文件字段（与后端一致）
      formData.append('enterpriseId', form.enterpriseId)

      if (form.enterpriseQualificationId !== null && form.enterpriseQualificationId !== undefined) {
         formData.append('enterpriseQualificationId', form.enterpriseQualificationId);
      }

      // 发送上传请求
      const response = await request.post(
         '/qualification/upload-file',  // 文件上传接口
         formData, {
         headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('park-token'),
            'Content-Type': 'multipart/form-data'
         },
         // 可选：显示上传进度
         onUploadProgress: (e) => {
            const percent = Math.round((e.loaded / e.total) * 100)
            options.onProgress({ percent })  // 传递进度给组件
         }
      }
      )

      if (response.success) {
         ElMessage.success('文件上传成功')
         dialogVisible.value = false;
         loadQualificationList(searchForm.enterpriseId)
         onSuccess(response.data)  // 通知组件上传成功
      } else {
         ElMessage.error('文件上传失败：' + response.message)
         onError(response.data)
      }
   } catch (err) {
      ElMessage.error('上传请求失败：' + (err.message || '网络错误'))
      onError(err)
   }
};

// 上传前校验文件类型
const handleBeforeUpload = (file) => {
   // 验证文件类型（el-upload 的 accept 只是前端过滤，这里做二次校验）
   // const acceptTypes = ['.jpg', '.jpeg', '.png', '.pdf', '.doc', '.docx', ".xls", ".xlsx", ".mp4"]
   // const fileExt = '.' + file.name.split('.').pop().toLowerCase()
   // if (!acceptTypes.includes(fileExt)) {
   //    ElMessage.error('仅支持上传 jpg、jpeg、png、pdf、doc、docx、xls、xlsx 、mp4格式文件')
   //    return false  // 阻止上传
   // }

   // 验证文件大小（el-upload 的 file-size 只是前端限制，这里做二次校验）
   if (file.size > 50 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过 50MB')
      return false  // 阻止上传
   }

   return true  // 允许上传
};

// 移除已上传文件
const handleFileRemove = () => {
   formRef.value.validateField('fileList')
};
// 超过文件数量限制时触发
const handleExceed = () => {
   ElMessage.warning('最多只能上传 1 个文件')
}

// 删除资质文件
const handleDelete = async (row) => {
   ElMessageBox.confirm('确认删除当前文件吗?')
      .then(() => {
         const loading = ElLoading.service({
            lock: true,
            text: '正在删除...',
            background: 'rgba(0, 0, 0, 0.7)',
         })
         request.get('/qualification/removeQualification', {
            params: {
               enterpriseQualificationId: row.enterpriseQualificationId
            }
         }).then(data => {
            if (data.success) {
               ElMessage.success('删除成功');
               loadQualificationList()
            } else {
               ElMessage.error(data.message);
            }
            loading.close()
         }).catch(err => {
            ElMessage.error('删除异常' + err);
            loading.close()
         })
      })
      .catch(() => {
         // catch error
      }).finally(() => {
      })
};


// 格式化文件大小（字节 → MB/KB）
const formatFileSize = (size) => {
   if (!size) return '0 KB';
   return size >= 1024 * 1024
      ? (size / (1024 * 1024)).toFixed(2) + ' MB'
      : (size / 1024).toFixed(2) + ' KB';
};
</script>

<style scoped>
.qualification-management {
   background-color: #fff;
   min-height: 100%;
}

.enterprise-selector {
   margin-bottom: 20px;
   padding: 10px;
   background-color: #f5f7fa;
   border-radius: 4px;
}

.qualification-table {
   margin-top: 10px;
}

.empty-tip {
   text-align: center;
   padding: 50px 0;
   color: #909399;
}

.preview-container {
   width: 100%;
   min-height: 500px;
   display: flex;
   justify-content: center;
   align-items: center;
}

.preview-image {
   max-width: 100%;
   max-height: 500px;
}

.preview-pdf {
   width: 100%;
   height: 500px;
}
</style>